package com.lst.projectlib.util;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Date;
import java.text.SimpleDateFormat;

/**
 * Created by Administrator on 2017/3/3.
 */

public class FileUtil {
    /**
     * 获取文件路径的uri
     * @param filePath
     * @param fileName
     * @return
     */
    public static Uri getOutputFileUri(String filePath, String fileName){
        return Uri.fromFile(getOutputFile(filePath, fileName));
    }

    /**
     * 创建或打开SD文件
     * @param filePath
     * @param fileName
     * @return
     */
    public static File getOutputFile(String filePath, String fileName){
        if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) return null;
        try{
            if(TextUtils.isEmpty(filePath)) filePath = "";
            File mediaStorageDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + filePath);
            // Create the storage directory if it does not exist
            if (!mediaStorageDir.exists()){
                if (!mediaStorageDir.mkdirs()){
                    return null;
                }
            }
            if(TextUtils.isEmpty(fileName)){
                return mediaStorageDir;
            }else {
                // Create a media file name
                File mediaFile = new File(mediaStorageDir, fileName);
                return mediaFile;
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 判断文件是否存在
     * @param filePath
     * @return
     */
    public static boolean isFileExist(String filePath){
        if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) return false;
        try{
            if(TextUtils.isEmpty(filePath)) return false;
            File mediaStorageDir = new File(filePath);
            return mediaStorageDir.exists();
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 复制文件到指定目录
     * @param fromFile
     * @param toFile
     */
    public static boolean copyFile(String fromFile, String toFile){
        InputStream fosfrom = null;
        OutputStream fosto = null;
        try{
            fosfrom = new FileInputStream(fromFile);
            fosto = new FileOutputStream(toFile);
            byte bt[] = new byte[2048];
            int c;
            while ((c = fosfrom.read(bt)) > 0){
                fosto.write(bt, 0, c);
            }
            fosfrom.close();
            fosto.close();
            return true;
        } catch (Exception ex){
            ex.printStackTrace();
            return false;
        } finally {
            try {
                fosfrom.close();
                fosto.flush();
                fosto.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 复制文件
     * @param fromFile
     * @param toFile
     * @return
     */
    public static boolean copyFile(File fromFile, File toFile){
        if (fromFile == null || toFile == null) return false;
        if (!fromFile.exists()) return false;
        if (!fromFile.isFile()) return false;
        if (!fromFile.canRead()) return false;

        return copyFile(fromFile.getAbsolutePath(), toFile.getAbsolutePath());
    }

    /**
     * 删除文件
     * @param file
     */
    public static void delete(File file){
        if (file==null) return;

        if (file.isFile()) {
            file.delete();
            return;
        }
        if (file.isDirectory()) {
            File[] childFiles = file.listFiles();
            if (childFiles == null || childFiles.length == 0) {
                file.delete();
                return;
            }

            for (int i = 0; i < childFiles.length; i++) {
                delete(childFiles[i]);
            }
            file.delete();
        }
    }

    /**
     * 将内容写入到文件中
     * @param file
     * @param string
     * @return
     */
    public static boolean writeStrToFile(File file, String string){
        if (file==null || TextUtils.isEmpty(string)) return false;
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            out.write(string.getBytes("UTF-8"));
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static boolean writeBitmapToFile(File file, Bitmap bitmap){
        if (file==null || bitmap==null) return false;

        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 从文件中读取str
     * @param file
     * @return
     */
    public static String readStrFromFile(File file){
        if (file==null) return null;
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            //把每次读取的内容写入到内存中，然后从内存中获取
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len =0;
            //只要没读完，不断的读取
            while((len=fileInputStream.read(buffer))!=-1){
                outputStream.write(buffer, 0, len);
            }
            //得到内存中写入的所有数据
            byte[] data = outputStream.toByteArray();
            return new String(data);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                fileInputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取图片的名字"IMG_20161215_211532"
     * @param fileSuffix
     * @return
     */
    public static String createFileNameYMD(String fileSuffix) {
        if(TextUtils.isEmpty(fileSuffix)) fileSuffix = "jpg";
        String fileName = "";
        Date date = new Date(System.currentTimeMillis()); // 系统当前时间
        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
        fileName = dateFormat.format(date) + "." + fileSuffix;
        return fileName;
    }

    /**
     * Gets the corresponding path to a file from the given content:// URI
     * @param context
     * @param contentUri
     * @return
     */
    public static String getFilePathFromContentUri(Context context, Uri contentUri) {
        String filePath = "";
        String[] filePathColumn = {MediaStore.MediaColumns.DATA};

        Cursor cursor = context.getContentResolver().query(contentUri, filePathColumn, null, null, null);
        if(cursor != null && cursor.moveToFirst()){
            try {
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                filePath = cursor.getString(columnIndex);
            }finally {
                cursor.close();
            }
        }
        return filePath;
    }
}
